package org.twnmayberry.ejb;

import java.util.List;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.twnmayberry.dto.POIDTO;


@MessageDriven(activationConfig={
        @ActivationConfigProperty(
                propertyName="destinationType",
                propertyValue="javax.jms.Topic"),            
        @ActivationConfigProperty(
                propertyName="destination",
                propertyValue="java:/topic/ejava/projects/datashare/dmv"),            
        @ActivationConfigProperty(
                propertyName="acknowledgeMode",
                propertyValue="Auto-acknowledge")            
})
public class MayberryMDB implements MessageListener {

	 private static final Log log = LogFactory.getLog(MayberryMDB.class);
	
	@EJB
	private PoiMgmtRemote poiManager;
	
	@Override
	public void onMessage(Message arg0) {
		try {
			log.info("MayberryMDB received message: " + arg0.getJMSMessageID());
		  String firstName = arg0.getStringProperty("firstName");
		  String middleName = arg0.getStringProperty("middleName");
		  String lastName = arg0.getStringProperty("lastName");
		  log.debug("Person: " + firstName + " " + middleName + " " + lastName);
		  List<POIDTO> pois = poiManager.getPOIsByName(firstName, middleName, lastName);
		  if(pois != null && pois.size() > 0) {
			  log.info("POI matches!  Publish change...");
			  for(POIDTO poi : pois) {
				  boolean danger = poiManager.isDangerous(poi);
			    poiManager.publishPOIChange(poi, danger);
			  }
		  } else {
			  log.info("No POI matches the DMV change");
		  }
		} catch (Exception e) {
			log.error("Error processing message: " + e);
		}
	}

}
